<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<el-row :gutter="20">
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_EntityType_FormItem"
							prop="Entity.EntityType"
							:rules="[{ required: true, message: '实体类型为必填项', trigger: 'blur' }]"
						>
							<template #label>
								<WtmLabelTooltip label="实体类型" tooltip="业务单据类型（使用模型名称）" />
							</template>
							<el-cascader
								class="width100"
								:options="stateData.allBillList"
								:props="{ checkStrictly: false, emitPath: false, label: 'Text', value: 'Id', children: 'Children' }"
								clearable
								filterable
								v-model="stateData.vmModel.Entity.EntityType"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_TargetType_FormItem"
							prop="Entity.TargetType"
							label="目标类型"
							:rules="[{ required: true, message: '目标类型为必填项', trigger: 'blur' }]"
						>
							<el-select v-model="stateData.vmModel.Entity.TargetType" clearable class="width100" @change="onTargetTypeChange">
								<el-option key="角色" value="角色" label="角色"></el-option>
								<el-option key="岗位" value="岗位" label="岗位"></el-option>
								<el-option key="部门" value="部门" label="部门"></el-option
							></el-select>
						</el-form-item>
					</el-col>

					<template v-if="stateData.vmModel.Entity.TargetType === '角色'">
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item
								ref="Entity_Roles_FormItem"
								prop="Entity.Roles"
								label="角色"
								:rules="[{ required: true, message: '角色为必填项', trigger: 'blur' }]"
							>
								<el-select v-model="stateData.vmModel.Entity.Roles" clearable class="width100">
									<el-option v-for="item in stateData.AllFrameworkRoles" :key="item.Value" :value="item.Value" :label="item.Text"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</template>

					<template v-if="stateData.vmModel.Entity.TargetType === '岗位'">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_GroupId_FormItem"
								prop="Entity.GroupId"
								label="部门"
								:rules="[{ required: true, message: '部门为必填项', trigger: 'blur' }]"
							>
								<el-cascader
									:options="stateData.AllFrameworkGroups"
									:props="{ checkStrictly: true, emitPath: false, label: 'Text', value: 'Value', children: 'Children' }"
									clearable
									filterable
									class="width100"
									v-model="stateData.vmModel.Entity.GroupId"
								/>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_JobPositionId_FormItem"
								prop="Entity.JobPositionId"
								label="岗位"
								:rules="[{ required: true, message: '岗位为必填项', trigger: 'blur' }]"
							>
								<el-select
									v-model="stateData.vmModel.Entity.JobPositionId"
									clearable
									class="width100"
									placeholder="请先选择部门"
									:disabled="!stateData.vmModel.Entity.GroupId"
								>
									<el-option v-for="item in stateData.AllSysJobPositions" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</template>

					<template v-if="stateData.vmModel.Entity.TargetType === '部门'">
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item
								ref="Entity_GroupId_FormItem"
								prop="Entity.GroupId"
								label="部门"
								:rules="[{ required: true, message: '部门为必填项', trigger: 'blur' }]"
							>
								<el-cascader
									:options="stateData.AllFrameworkGroups"
									:props="{ checkStrictly: true, emitPath: false, label: 'Text', value: 'Value', children: 'Children' }"
									clearable
									filterable
									class="width100"
									v-model="stateData.vmModel.Entity.GroupId"
								/>
							</el-form-item>
						</el-col>
					</template>

					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_Scope_FormItem"
							prop="Entity.Scope"
							label="权限范围"
							:rules="[{ required: true, message: '权限范围为必填项', trigger: 'blur' }]"
						>
							<el-select v-model="stateData.vmModel.Entity.Scope" clearable class="width100">
								<el-option key="仅本人" value="仅本人" label="仅本人"></el-option>
								<el-option key="本部门" value="本部门" label="本部门"></el-option>
								<el-option key="本部门及下级" value="本部门及下级" label="本部门及下级"></el-option>
								<el-option key="指定部门" value="指定部门" label="指定部门"></el-option>
								<el-option key="全部" value="全部" label="全部"></el-option>
								<el-option key="自定义" value="自定义" label="自定义"></el-option
							></el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_CustomCondition_FormItem" prop="Entity.CustomCondition" label="自定义条件">
							<el-input v-model="stateData.vmModel.Entity.CustomCondition" clearable class="width100"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_Priority_FormItem"
							prop="Entity.Priority"
							label="优先级"
							:rules="[{ required: true, message: '优先级为必填项', trigger: 'blur' }]"
						>
							<el-input-number v-model="stateData.vmModel.Entity.Priority" clearable class="width100"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_IsEnabled_FormItem"
							prop="Entity.IsEnabled"
							label="是否启用"
							:rules="[{ required: true, message: '是否启用为必填项', trigger: 'blur' }]"
						>
							<el-select v-model="stateData.vmModel.Entity.IsEnabled" clearable class="width100">
								<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
								<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, nextTick, ComponentInternalInstance, watch } from 'vue';
import { SysDataPrivilegeApi as api } from '/@/views/_admin/sysdataprivilege/api';
import other from '/@/utils/other';
import { ISysDataPrivilegeVm } from '/@/views/_admin/sysdataprivilege/api/interface';
import { IViewModel } from '/@/types/common';

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);
const stateData = reactive<IViewModel<ISysDataPrivilegeVm>>({
	vmModel: {
		Entity: {
			EntityType: null,
			TargetType: '角色',
			TargetId: null,
			Scope: '仅本人',
			CustomCondition: null,
			Priority: 0,
			IsEnabled: false,
			GroupId: null,
			JobPositionId: null,
			Roles: null,
		},
		GroupId: null,
		ActionName: null,
		IsMyApprove: null,
	},
	allBillList: [],
	AllFrameworkGroups: [],
	AllSysJobPositions: [],
	AllFrameworkRoles: [],
});

const handleApiResponse = (response: any) => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	emit('refresh');
	loading.value = false;
	closeDialog();
};

const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response))
				.catch(handleError);
		}
	});
};
// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {},
		false
	);
};
// 监听部门选择变化
watch(
	() => stateData.vmModel.Entity.GroupId,
	(newGroupId) => {
		if (newGroupId) {
			stateData.vmModel.Entity.JobPositionId = null;
			getSysJobPositions(newGroupId);
			if (stateData.vmModel.Entity.TargetType === '部门') {
				stateData.vmModel.Entity.TargetId = newGroupId;
			}
		} else {
			stateData.AllSysJobPositions = [];
			stateData.vmModel.Entity.JobPositionId = null;
		}
	}
);
// 新增watch: 岗位
watch(
	() => stateData.vmModel.Entity.JobPositionId,
	(newJobPositionId) => {
		if (stateData.vmModel.Entity.TargetType === '岗位') {
			stateData.vmModel.Entity.TargetId = newJobPositionId;
		}
	}
);
// 新增watch: 角色
watch(
	() => stateData.vmModel.Entity.Roles,
	(newRoles) => {
		if (stateData.vmModel.Entity.TargetType === '角色') {
			if (Array.isArray(newRoles)) {
				stateData.vmModel.Entity.TargetId = newRoles[0] || null;
			} else {
				stateData.vmModel.Entity.TargetId = newRoles;
			}
		}
	}
);
// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
		other.getSelectList('/api/SysDataPrivilege/GetBillList', [], false).then((x) => {
			stateData.allBillList = x;
		}),
		// 加载部门数据
		other.getSelectList('/api/common/GetGroups?auth=false', [], false).then((x) => {
			stateData.AllFrameworkGroups = x;
		}),

		// 加载角色数据
		other.getSelectList('/api/SysJobPosition/GetFrameworkRoles', [], false).then((x) => {
			stateData.AllFrameworkRoles = x;
		}),
	]);
};
// 获取岗位数据的方法
const getSysJobPositions = (groupId?: string) => {
	const url = groupId ? `/api/SysUserJobPosition/GetSysJobPositions?groupId=${groupId}` : '/api/SysUserJobPosition/GetSysJobPositions';
	return other.getSelectList(url, [], false).then((x) => {
		stateData.AllSysJobPositions = x;
	});
};
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 目标类型改变时的处理
const onTargetTypeChange = (value: string) => {
	if (value === '岗位') {
		stateData.vmModel.Entity.GroupId = null;
		stateData.vmModel.Entity.JobPositionId = null;
	} else if (value === '部门') {
		stateData.vmModel.Entity.GroupId = null;
		stateData.vmModel.Entity.JobPositionId = null;
	} else if (value === '角色') {
		stateData.vmModel.Entity.GroupId = null;
	}
};

const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSave,
			visible: true,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>
